# -*- coding: UTF-8 -*-
import os
import sys
import traceback
import logging
from logging.handlers import RotatingFileHandler


def init_logging(loger_name):
    current_dir = os.path.dirname(os.path.realpath(__file__))
    logger = logging.getLogger(loger_name)
    formatter = logging.Formatter(
        '[%(asctime)s] %(levelname)s File [%(filename)s] '
        'in [%(funcName)s] [line:%(lineno)d] %(message)s')
    error_log = os.path.join(current_dir, 'logs/%s_err.log' % loger_name)
    if not os.path.exists(os.path.dirname(error_log)):
        os.makedirs(os.path.dirname(error_log))
    error_file_handler = RotatingFileHandler(
        error_log,
        maxBytes=512 * 1024 * 1024,
        backupCount=2
    )
    error_file_handler.setLevel(logging.ERROR)
    error_file_handler.setFormatter(formatter)
    logger.addHandler(error_file_handler)

    info_log = os.path.join(current_dir, 'logs/%s_info.log' % loger_name)
    info_file_handler = RotatingFileHandler(
        info_log,
        maxBytes=512 * 1024 * 1024,
        backupCount=2
    )
    info_file_handler.setLevel(logging.INFO)
    info_file_handler.setFormatter(formatter)
    logger.addHandler(info_file_handler)
    logger.setLevel(logging.DEBUG)
    return logger


def format_exc_all():
    _, exe_obj, tb = sys.exc_info()
    excepts = traceback.extract_tb(tb)
    rets = ''
    glue = ''
    for exc in excepts:
        filename, lineno, funname, line = exc
        try:
            rets += glue + \
                '{}:{}, in {}    {}  {}'.format(
                    filename, lineno, funname, line, str(exe_obj).decode('unicode_escape'))
        except Exception as e:
            pass
        glue = ' | '
    return "[%s]" % rets
